package com.erebus.config;

import com.erebus.model.dto.UserExt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.Key;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


// 自定义认证成功处理器
@Component
public class CustomHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {

        // 构建你要返回的 token 或用户信息
        String token = generateToken(authentication);

        // 设置响应格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"token\": \"" + token + "\"}");
        response.setStatus(HttpServletResponse.SC_OK);
    }

    private String generateToken(Authentication authentication) {
        // 从 Authentication 中获取 userExt
        UserExt userExt = (UserExt) authentication.getPrincipal();

        // 自定义密钥（确保长度 ≥ 32 字节）
        String secretString = "mis77mis77mis77mis77mis77mis7777"; // 32 字符，符合 HS256 要求
        Key secretKey = new SecretKeySpec(secretString.getBytes(), "HmacSHA256");

        // 设置过期时间：24小时后
        Instant now = Instant.now();
        Instant expiration = now.plus(1, ChronoUnit.DAYS); // 使用 java.time.Duration 也可以

        // 构建自定义 claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", userExt.getUsername());
        claims.put("password", userExt.getPassword()); // 不建议放密码！仅演示
        claims.put("name", userExt.getName());
        claims.put("phone", userExt.getPhone());
        claims.put("openid", userExt.getOpenid());
        claims.put("userId", "fsdfsd");

        return Jwts.builder()
                .claims(claims) // 添加所有 claims
                .subject(userExt.getUsername()) // 替代 setSubject
                .issuedAt(Date.from(now)) // 替代 setIssuedAt
                .expiration(Date.from(expiration)) // 替代 setExpiration
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact(); // 生成 token 字符串
    }
}